<template>
  <el-container>
    <el-main>
      <div class="app-main" style="width: 900px">
        <div v-show="this.case_statusNum != 1" class="filter-container">
          <div class="check_group">
            <el-tabs
              ref="titleBadge"
              class="deleteBorder"
              v-model="statusAll"
              fill="＃F56C6C"
              @tab-click="handleFilter()"
            >
              <el-tab-pane label="进行中" value="进行中" name="进行中">
                <span slot="label">
                  进行中
                  <el-badge :value="count_progress"> </el-badge
                ></span>
              </el-tab-pane>
              <el-tab-pane label="全部" name="全部" value="全部">
                <span slot="label">
                  全部<el-badge :value="total" type="info"> </el-badge
                ></span>
              </el-tab-pane>
              <el-tab-pane label="已存档" name="已存档" value="已存档">
                <span slot="label">
                  已存档
                  <el-badge :value="count_archive" type="warning"> </el-badge
                ></span>
              </el-tab-pane>
              <el-tab-pane label="已完成" value="已完成" name="已完成">
                <span slot="label">
                  已完成
                  <el-badge :value="count_finished" type="success"> </el-badge
                ></span>
              </el-tab-pane>
            </el-tabs>
          </div>
          <div class="option">
            <el-button size="small" type="primary" @click="handleCreate">
              添加案件
            </el-button>
          </div>
        </div>
        <div class="searchBox">
          <el-input
            v-model="listQuery.keyword"
            size="medium"
            placeholder="请输入案件编号或案件标题进行搜索"
            class="filter-item"
            prefix-icon="iconfont el-icon-search "
            @keyup.enter.native="handleFilter"
          />
          <el-select
            size="small"
            v-model="listQuery.sort_order"
            @change="handleFilter"
            placeholder="最新在前"
          >
            <el-option
              v-for="item in optiondate"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <el-table
          ref="recordTable"
          v-el-table-infinite-scroll="load"
          :data="list"
          stripe
          fit
          :show-header="false"
          highlight-current-row
          :height="tableHeight"
        >
          <!-- @row-click="send" -->
          <el-table-column>
            <!-- <template slot-scope="{ row, $index }"> -->
                 <template slot-scope="{ row }">
              <div class="clearfix">
                <!-- #<span style="margin-right: 5px">{{ $index + 1 }} |</span> -->
                <!-- <router-link @click.native="sessionStorage.setItem('rowkey', JSON.stringify(row))" :to="{ name: 'Form'}"> -->
                <router-link  @click.native="sendsession(row)" :to="{ name: 'Form'}">
                <!-- <router-link :to="{ name: 'Form', params: { shuju: row } }"> -->
                  
                  <span
                    style="
                      font-weight: bold;
                      margin-right: 5px;
                      color: #222222;
                      font-size: 18px;
                    "
                  >
                    {{ row.case_name }}</span
                  >
                </router-link>
                <el-tag size="small" :type="row.case_status | statusFilter">
                  {{ row.case_status }}
                </el-tag>
              </div>
              <div class="text item">
                <el-row>
                  <el-col :span="20">
                    <div class="middle" style="color: #666666">
                      <label style="margin-right: 10px"> 案件编号: </label>
                      <span>{{ row.case_number }} </span>
                      <label style="margin-right: 10px; margin-left: 18px"
                        >承办人:</label
                      >
                      <span style="margin-left: 1px; color: #666666">{{
                        row.case_examiner != null
                          ? row.case_examiner.join(",")
                          : null
                      }}</span>
                    </div>
                    <div class="message">
                      <label>由</label>
                      <span
                        style="
                          margin-right: 6px;
                          margin-left: 4px;
                          color: #666666;
                        "
                        >{{ row.case_creater }}</span
                      >
                      <label style="margin-right: 5px">创建于</label>
                      <span style="margin-right: 5px; color: #666666">{{
                        row.start_time | parseTime
                      }}</span>
                      <el-tag
                        style="margin: 0.5px;color:#000000"
                        v-for="item in row.label"
                        :key="item.name"
                        :color="item.color"
                        size="mini"
                      >
                        {{ item.name }}</el-tag>
                    </div>
                  </el-col>
                  <el-col :span="4">
                    <div class="remark">
                      <div style="font-size: 20px">
                        <el-badge :value="200" :max="12" class="item">
                          <svg-icon icon-class="remark" class-name="remark" />
                        </el-badge>
                        <el-badge
                          :value="200"
                          :max="3"
                          class="item"
                          type="primary"
                          style="margin-left: 5px"
                        >
                          <svg-icon
                            style="margin-left: 20px"
                            icon-class="thumb"
                            class-name="thumb"
                          />
                        </el-badge>
                      </div>
                      <span
                        class="item"
                        style="margin: 0pxmessag; color: #666666"
                        >更新于一星期前</span
                      >
                    </div>
                  </el-col>
                </el-row>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-alert
          v-if="isloading"
          title="正在努力加载中..."
          type="success"
          center
          :closable="false"
          show-icon
        />
        <el-alert
          v-if="noMore"
          title="没有更多啦！"
          type="warning"
          center
          show-icon
        />

        <el-dialog
          style="width: 60%"
          :title="textMap[dialogStatus]"
          :visible.sync="dialogFormVisible"
          class="createCase"
        >
          <el-form
            ref="dataForm"
            label-width="80px"
            :rules="rules"
            :model="temp"
            label-position="left"
            style="width: 85%; margin-left: 30px"
          >
            <el-form-item
              disabled="disabled"
              label="案件编号"
              prop="case_number"
            >
              <el-input size="small" v-model="temp.case_number" />
            </el-form-item>
            <el-form-item label="案件名称" prop="case_name">
              <el-input size="medium" v-model="temp.case_name" />
            </el-form-item>
            <el-form-item label="承办人员" prop="case_examiner">
              <el-select
                size="small"
                v-model="temp.case_examiner"
                filterable
                multiple
                prefix-icon="iconfont el-icon-search "
                placeholder="请选择"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="创建日期" prop="start_time">
              <el-date-picker
                size="small"
                v-model="temp.start_time"
                type="datetime"
                disabled="disabled"
                placeholder="Please pick a date"
              />
            </el-form-item>
            <el-form-item label="常用标签" prop="label">
              <el-select
                size="small"
                v-model="temp.label"
                value-key="name"
                filterable
                multiple
                placeholder="请选择"
              >
                <el-option
                  v-for="item in labelsx"
                  :key="item.name"
                  :label="item.name"
                  :value="item"
                >
                <div class="optionstyle" > 
                   <div class="optiontest" :style="'background-color:'+item.color"> </div>
                  <div class="optionlabel" >{{item.name}} </div>
                </div>
               
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              v-if="dialogStatus != 'create'"
              label="案件状态"
              prop="case_status"
            >
              <el-select v-model="temp.case_status" placeholder="请选择">
                <el-option
                  v-for="item in statusOptions"
                  :key="item"
                  :label="item"
                />
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false"> 取消</el-button>
            <el-button
              type="primary"
              @click="dialogStatus === 'create' ? createData() : updateData()"
            >
              确认
            </el-button>
          </div>
        </el-dialog>
      </div>
    </el-main>
  </el-container>
</template>
<script>
import {
  fetchList,
  createArticle,
  updateArticle,
  delectData,
} from "@/api/article";
import waves from "@/directive/waves"; // waves directive
import { parseTime } from "@/utils/index";
import {fetchLabel} from "@/api/labels"
//import   indexdata from "./indexdata.json";
const calendarTypeOptions = [
  { key: "Finish", display_name: "已完成" },
  { key: "Waiting", display_name: "已存档" },
  { key: "Doing", display_name: "进行中" },
];
const labelOptions = ["涉毒", "涉黄", "教育相关", "医疗相关"];
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name;
  return acc;
}, {});

export default {
  name: "ComplexTable",

  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        已存档: "success",
        进行中: "info",
        已完成: "danger",
      };
      return statusMap[status];
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type];
    },
    parseTime: parseTime,
  },
  data() {
    return {
      labelsx:[],
      statusAll: "进行中",
      value: "",
      row: "",
      refNamePopover: "popover-",
      tableHeight: 50,
      case_statusNum: this.$route.name,
      noMore: false,
      isloading: false,
      options: [
        {
          value: "张扬",
          label: "刘扬",
        },
        {
          value: "张扬2",
          label: "赵健书",
        },
        {
          value: "张扬1",
          label: "刘鑫",
        },
        {
          value: "张扬13",
          label: "菲菲",
        },
        {
          value: "张扬14",
          label: "吴亦凡",
        },
      ],
      optiondate: [
        {
          value: "-1",
          label: "最新在前",
        },
        {
          value: "1",
          label: "最早在前",
        },
      ],
      inputVisible: false,
      inputValue: "",
      labels: labelOptions,
      isIndeterminate: true,
      tableKey: 0,
      list: [],
      tot: 0,
      total: 0,
      count_archive: 0,
      count_finished: 0,
      count_progress: 0,
      loading: false,
      listQuery: {
        page: 1,
        page_size: 20,
        status: null,
        // case_creater: "吴亦凡",
        sort_order: "-1",
        keyword: null,
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      statusOptions: ["已存档", "进行中", "已完成"],
      showReviewer: false,
      temp: {
        id: undefined,
        case_number: null,
        case_name: "",
        case_examiner: "",
        case_creater: "",
        start_time: new Date(),
        // label: this.dynamicTags,
        label: [],
        case_status: "",
      },
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑案件",
        create: "创建案件",
      },

      pvData: [],
      rules: {
        case_status: [
          { required: true, message: "状态不能为空", trigger: "blur" },
        ],
        start_time: [
          { required: true, message: "创建时间不能为空", trigger: "blur" },
        ],
        case_name: [
          { required: true, message: "案件名称不能为空", trigger: "blur" },
        ],
        case_number: [
          { required: true, message: "案件编号不能为空", trigger: "blur" },
        ],
        case_examiner: [
          { required: true, message: "承办人不能为空", trigger: "blur" },
        ],
        case_creater: [
          { required: true, message: "创建人员不能为空", trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    this.$nextTick(() => {
      // 根据浏览器高度设置初始高度
      this.tableHeight =
        window.innerHeight - this.$refs.recordTable.$el.offsetTop - 70;
      // 监听浏览器高度变化，改变表格高度
      window.onresize = () => {
        this.tableHeight =
          window.innerHeight - this.$refs.recordTable.$el.offsetTop - 70;
      };
    });
  },
  created() {
    this.getList();
  },
  methods: {
    sendsession(row){
      sessionStorage.setItem("rowkey",JSON.stringify(row))
    },
    load() {
      // this.isloading = true
      // noMore 没有更多
      // isloading   正在加载

      if (this.list.length >= this.tot) {
        this.isloading = false;
        // this.noMore = true
      } else if(this.list.length==this.listQuery.page*this.listQuery.page_size) {
        this.listQuery.page++;
        this.getList();
      }
      // this.isloading = false
    },
    getList() {
      
      if(this.$route.meta.title=="案件列表"){
        if (this.statusAll == "全部" || this.statusAll == 0) {
        this.listQuery.case_status = null;
      } else {
        this.listQuery.case_status = this.statusAll;
      }
      }else if(this.$route.meta.title!="案件列表" ){
        this.listQuery.case_status=this.$route.meta.title
      }
      
      // this.loading = true
      fetchList(this.listQuery).then((response) => {
        this.count_archive = response.data.count_archive;
        this.count_finished = response.data.count_finished;
        this.count_progress = response.data.count_progress;
        this.total =
          this.count_archive + this.count_finished + this.count_progress;
        this.$refs.titleBadge.$children[0].$forceUpdate();
        for (let i in response.data.list) {
          this.list.push(JSON.parse(JSON.stringify(response.data.list[i])));
        }
        switch (this.statusAll) {
        case "全部":
          this.tot = this.total;
          break;
        case "进行中":
          this.tot = this.count_progress;
          break;
        case "已存档":
          this.tot = this.count_archive;
          break;
        case "已完成":
          this.tot = this.count_finished;
          break;
      }
      });
    },
    getLabels(){
      this.labelsx=[]
      fetchLabel().then((response)=>{
        for (let i in response.data.list) {
            this.labelsx.push(JSON.parse(JSON.stringify(response.data.list[i])));  
          }
      })
    },
    handleFilter(tab,event) {
      this.list.length = 0;
      this.listQuery.page = 1;
      if (this.listQuery.keyword == "") {
        this.listQuery.keyword = null;
      }
      
      this.list = [];
      if (this.list.length == 0) {
        this.getList();
      } else {
        this.handleFilter;
      }
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        case_number: null,
        case_name: "",
        case_examiner: "",
        case_creater: "",
        start_time: new Date(),
        label: [],
        case_status: "",
      };
      // const tempData = Object.assign({}, this.temp)
      // tempData.start_time=+new Date(tempData.start_time)
    },
    handleCreate() {
      this.getLabels();
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
    },
    createData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          // this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          this.temp.case_status = "进行中";
          this.temp.case_creater = "莱昂纳多";
          this.temp.start_time = +new Date(this.temp.start_time);
          this.temp.start_time = this.temp.start_time
            .toString()
            .substring(0, 10);
          createArticle(this.temp).then((response) => {
            if (response.msg == "该案件编号已存在") {
              this.$notify.error({
                message: "该案件编号已存在",
                duration: 2000,
              });
            } else {
              this.$nextTick(() => {
                this.list = [];
                this.getList();
              });
              this.$notify({
                // title: "Success",
                message: "创建成功",
                type: "success",
                duration: 2000,
              });
            }
            this.dialogFormVisible = false;
          });
        }
      });
    },
    handleUpdate(row) {
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.temp = row;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    updateData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          // const tempData = Object.assign({}, this.temp)
          // tempData.start_time = +new Date(tempData.start_time) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateArticle(this.temp).then((response) => {
          
            // const index = this.list.findIndex((v) => v.id === this.temp.id);
            // this.list.splice(index, 1, this.temp)
            console.log(response);
            this.dialogFormVisible = false;
            this.$notify({
              message: "更新成功",
              type: "success",
              duration: 2000,
            });
          });
        }
      });
    },
    handleDelete(rownum, index) {
      delectData(rownum).then((response) => {
        let refName = this.refNamePopover + rownum;
        this.$refs[refName].doClose();
        console.log(response);
        if (response.code == 2000) {
          this.$notify({
            message: "删除成功",
            type: "success",
            duration: 2000,
          });
        }
      });

      // this.list.splice(index, 1)
    },
    formatJson(filterVal) {
      return this.list.map((v) =>
        filterVal.map((j) => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
    // loadMore() {
    //   if (this.loadSign) {
    //     this.loadSign = false
    //     this.page++
    //     if (this.page > 10) {
    //       return
    //     }
    //     setTimeout(() => {
    //       this.loadSign = true
    //     }, 1000)
    //     console.log('到底了', this.page)
    //   }
    // },
    send(row, event, column) {
      //this.listQuery.id='c08c22c5'
      console.log(111 + row.id);
      this.$router.push({ name: "Form", params: { rowkey: row } });
    },

    handleClose(tag) {
      this.temp.label.splice(this.temp.label.indexOf(tag), 1);
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue != null && this.labels.indexOf(inputValue) <= -1) {
        this.labels.push(inputValue);
      } else {
        this.$message({
          message: "不能重复添加标签",
          type: "warning",
        });
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    handleData(tag) {
      let inputValue = tag;
      if (inputValue != null && this.temp.label.indexOf(inputValue) <= -1) {
        this.temp.label.push(inputValue);
      } else {
        this.$message({
          message: "不能重复添加标签",
          type: "warning",
        });
      }
      this.inputVisible = false;
    },
    cancelDelete(id) {
      let refName = this.refNamePopover + id;
      this.$refs[refName].doClose();
    },
    sortChange() {
      if (this.listQuery.sort_order == "-1") {
        this.list = [];
        this.listQuery.sort_order = "1";
        this.listQuery.page = 1; // sort=1代表升序
        this.getList();
      } else {
        this.list = [];
        this.listQuery.sort_order = "-1";
        this.listQuery.page = 1; // sort =-1代表降序
        this.getList();
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.check_group {
  letter-spacing: 2px;
  width: 300px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 20px;
}
.el-radio__input {
  display: none;
}
.el-dialog {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.el-main {
  display: flex;
  justify-content: center;
}
.filter-container {
  height: 47px;
  border-top: 1px solid #e8e8e8;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #ffffff;
  padding: 0 16px;
  .filter-item:hover {
    border-color: #63a6e9;
    box-shadow: 0 0 4px rgb(99 166 233 / 40%);
  }
}
.searchBox {
  border-bottom: 1px solid #e8e8e8;
  border-top: 1px solid #e8e8e8;
  padding: 0 16px;
  background-color: #fafafa;
  height: 70px;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  ::v-deep .filter-item input {
    //width: 75%;
    padding-right: 10px;
    height: 32px;
  }
}
.createCase::v-deep.el-dialog__wrapper {
  overflow-y: hidden;
  margin: auto;
  width: 100;
}

.deleteBorder ::v-deep .el-tabs__nav-wrap::after {
  height: 0px;
  background: #fff;
}
.message {
  margin: 10px 0;
}
#coldiv {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}
.el-table span {
  margin-right: 15px;
}
.el-table label {
  color: #999999;
  font-weight: 400;
}
.el-table ::v-deep td,
::v-deep .cell {
  border-bottom: 0px;
  padding: 0px;
}
.item {
  margin: 10px 0 0 0;
  color: #000000;
}
.text {
  padding: 0px 0px 10px 10px;
}
.clearfix {
  border: 0px;
  padding: 18px 30px 0 10px;
  span{
    font-size: 15px;
  }
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
.message{
  el-tag{
    span{
      color: #333333;
    };
  }
}
.optiontest{
  height: 20px;
  width: 20px;
  //background-color: #000000;
  border-radius: 5px;
}
.optionstyle{
  display: flex;
  margin-top: 5px;
}
.optionlabel{
  
  height: 20px;
  line-height: 20px;
  margin-left: 10px;
}
</style>
